#!/usr/bin/php -d display_errors

<?php

define ("EXIT_EARG", 10);
define ("EXIT_EAPI", 20);
define ("ABF_URL", "https://abf.io/api/v1/");

$API_TOKEN = getenv("API_TOKEN");
if (empty($API_TOKEN)) {
	fwrite(STDERR, "Define ABF API_TOKEN in API_TOKEN env!" . PHP_EOL);
	exit(1);
}

// https://www.php.net/manual/ru/book.curl.php
// https://rosa-abf.github.io
function _curl_abf($url) {
	global $API_TOKEN;
	$full_url = ABF_URL . $url;
	$c = curl_init();
	curl_setopt($c, CURLOPT_URL, $full_url);
	curl_setopt($c, CURLOPT_USERPWD, $API_TOKEN . ":");
	curl_setopt($c, CURLOPT_VERBOSE, false);
	curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($c, CURLOPT_FAILONERROR, true);
	$r = curl_exec($c);
	$code = curl_getinfo($c, CURLINFO_RESPONSE_CODE);
	if ( !( ($code >= 200) && ($code < 300) ) ) {
		fwrite(STDERR, "ABF API has returned an error, code " . $code . PHP_EOL . "URL was: " . $full_url . PHP_EOL);
		if ($code == 404) {
			fwrite(STDERR, "Probably invalid build list ID." . PHP_EOL);
		}
		if ($code == 401) {
			fwrite(STDERR, "Probably invalid ABF API_TOKEN." . PHP_EOL);
		}
		return false;
	}
	return $r;
}

function _get_containers_chain($buidlistid) {
	// r - response raw, rd - responce decoded
	$rr = _curl_abf("build_lists/" . $buidlistid . ".json");
	if ($rr == false) {
		return false;
	}
	$rd = json_decode($rr, true);
	$have_containers = false;
	foreach($rd['build_list']['extra_build_lists'] as $path) {
		echo $path['container_path'] . PHP_EOL;
		$have_containers = true;
	}
	if ($have_containers == false) {
		fwrite(STDERR, "This build list " . $buidlistid . " has no attached containers." . PHP_EOL);
	}
	// container of the current build list itself
	$path = $rd['build_list']['container_path'];
	if (empty($path)) {
		fwrite(STDERR, "No container for this build list  " . $buidlistid . " itlsef!" . PHP_EOL);
	} else {
		$have_containers = true;
		echo $path . PHP_EOL;
	}
	// return !=0 if no containers have been found
	return $have_containers;
}

switch ($argv[1]) {
	// gc - get chain
	case 'gc':
		//fwrite(STDERR, "Getting URLs to a chain of containers..." . PHP_EOL);
		if ( (!isset($argv[2])) || (!ctype_digit($argv[2])) ) {
			fwrite(STDERR, "Error! Usage example:" . PHP_EOL . $argv[0] . " gc 555444" . PHP_EOL . "where 555444 is a build list ID." . PHP_EOL);
			exit(EXIT_EARG);
		}
		$r = _get_containers_chain($argv[2]);
		if ($r == false) {
			exit(EXIT_EAPI);
		}
		break;
	case 'help':
	default:
		fwrite(STDERR, "Usage:" . PHP_EOL .
		               $argv[0] . " action [params]" . PHP_EOL .
		               "gc — get URLs of a chain of containers; example: " . $argv[0] . " gc 555444" . PHP_EOL .
		               "where 555444 is a build list ID." . PHP_EOL);
		exit(EXIT_EARG);
}

?>
